package uk.org.landeg.euler.problems;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import uk.org.landeg.euler.problems.framework.AbstractProblem;
import uk.org.landeg.euler.problems.framework.ProblemLauncher;

public class Problem022 extends AbstractProblem{
	public static void main(String[] args) {
		ProblemLauncher launcher = new ProblemLauncher(new Problem022());
		launcher.solve();		
	}
	
	@Override
	public String getDescription() {
		// TODO Auto-generated method stub
		return "What is the total of all the name scores in the file?";
	}

	@Override
	public Integer getProblemNumber() {
		// TODO Auto-generated method stub
		return 22;
	}		


	ArrayList<String> names;
	
	private int loadNames () throws IOException {
		notes.add("Loading names");
		names = new ArrayList<String>();
		BufferedReader reader = new BufferedReader(new FileReader("data/names.txt"));
		String line = reader.readLine();
		Pattern p = Pattern.compile("\\w+");
		Matcher m = p.matcher(line);
		while (m.find()) {
			names.add(m.group());
		}
		return names.size();
	}
	
	@Override			

	public Object solve() {
		try {
			loadNames();
			Collections.sort(names);
			long score = 0;
			long nameScore;
			int nameId = 0;
			for (String name : names) {
				nameId++;
				nameScore = 0;
				for (char ch : name.toCharArray()) {
					nameScore += (int)ch - (int)'A' + 1;
				}
				score += nameScore * nameId;
			}
			return score;
		} catch (IOException e) {
			e.printStackTrace();
			return 0;
		}
	}

}
